<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 巡展同步扩展类
 * @author Administrator
 *
 */
class XunSync{
    var $client = null;//连接客户端对象
    var $singleProcessModel = NULL;//单店主线流程模型
    var $xunProcessModel = NULL;//巡展主线流程模型
    var $xProjectModel = NULL;//巡展模型
    var $xPGxModel = NULL;//巡展广宣模型
    var $xPOfflineModel = NULL;//巡展线下模型
    var $xPODetailModel = NULL;//巡展线下明细模型
    var $sellpointModel = NULL;//专营店模型
    var $timeUnitModel = NULL;//时间单元模型
    var $xDataLogModel = NULL;
    var $json = array(
        'code'=>0,//状态码（0：错误，1：成功）
        'msg'=>'',//状态信息
        'data' => array(),//返回数据
    );
    function XunSync(){
        //自定义类使用CI资源使用此方法
        $CI =& get_instance();
        //载入xml解析类
        $CI->load->library('XMLParserLib');
        //单店主线流程模型
        $CI->load->model('singleProcessModel');
        $this->singleProcessModel = $CI->singleProcessModel;
        //巡展主线流程模型
        $CI->load->model('xunProcessModel');
        $this->xunProcessModel = $CI->xunProcessModel;
        //巡展模型
        $CI->load->model('xProjectModel');
        $this->xProjectModel = $CI->xProjectModel;
        //巡展广宣模型
        $CI->load->model('xPGxModel');
        $this->xPGxModel = $CI->xPGxModel;
        //巡展线下模型
        $CI->load->model('xPOfflineModel');
        $this->xPOfflineModel = $CI->xPOfflineModel;
        //巡展线下明细模型
        $CI->load->model('xPODetailModel');
        $this->xPODetailModel = $CI->xPODetailModel;
        //专营店模型
        $CI->load->model('sellpointModel');
        $this->sellpointModel = $CI->sellpointModel;
        //时段模型
        $CI->load->model('timeUnitModel');
        $this->timeUnitModel = $CI->timeUnitModel;
        //同步数据日志
        $CI->load->model('xDataLogModel');
        $this->xDataLogModel = $CI->xDataLogModel;
        //初始化Nusoap类
        $CI->load->library('Nusoap');
        //线上正式地址(公网)
        //$url = 'http://210.21.81.137/services/ProjectService?wsdl';
        //线上正式地址（内网）
        $url = 'http://172.28.216.8/services/ProjectService?wsdl';
        //线上测试地址
        //$url ="http://172.25.185.77/services/ProjectService?wsdl";
        //本地调试地址
        //$url ="http://202.96.191.254/services/ProjectService?wsdl";
        
        $this->client = new mynusoap_client($url, true);
        $this->client->soap_defencoding = 'UTF-8';
        $this->client->decode_utf8      = false;
        $this->client->xml_encoding     = 'UTF-8';
    }
    /**
     * 设置错误
     * @param string $msg
     * @param array $data
     */
    function setError($msg = '', $data = array()){
        $this->json['code'] = 0;
        $this->json['msg'] = $msg;
        $this->json['data'] = $data;
    }
    /**
     * 设置正确
     * @param string $msg
     * @param array $data
     */
    function setSuccess($msg = '', $data = array()){
        $this->json['code'] = 1;
        $this->json['msg'] = $msg;
        $this->json['data'] = $data;
    }
    /**
     * 更新接口状态
     * 审核状态：0表示未审核，1表示通过，2表示不通过， 3表示部分通过,4表示未提交,5返回修改
     * @param string $siteId 站点ID
     * @param int $status 状态
     * @return mixed|boolean
     */
    function updateSettleStatus($siteId, $status){
        //$result = $this->client->call('updateActivitySummary', array('in0'=>base64_decode($siteId), 'in1'=>base64_decode($status)));
        $result = $this->client->call('updateActivitySummary', array('in0'=>$siteId, 'in1'=>$status));
        $err = $this->client->getError();
        if ($err){
            $this->setError($err);
        }else{
            $xml = str_replace('&', '&amp;', $result['out']);
            $parser = new XMLParser($xml);
            $parser->Parse();
            $globalInfo = $parser->document->globalinfo[0];
            if($globalInfo->code[0]->tagData == 0 && $globalInfo->message[0]->tagData == "update_success"){
                $this->setSuccess('更新状态成功');
            }else{
                $this->setError('更新状态失败');
            }
        }
        return $this->json;
    }
    /**
     * 项目预算同步
     * @param int $year 年
     * @param int $month 月
     * @param number $listNumber 返回的最大行数（获取条数）
     * @param number $beginNumber 开始行数（表示页码，三观已毁）
     * @param string $state 项目状态 （08为默认值，表示已申请结算，RMP这边只获取这个状态的数据）
     * @param number $sign 获取标识（0：待同步，1：已同步）
     * @return Ambigous <number, multitype:number string multitype: , string, unknown>
     */
    function budgetProjectSync($year, $month, $listNumber = 10, $beginNumber = 1, $state = '08', $sign = 0){
        $startTime = microtime(true);
        $param = "<?xml version='1.0' encoding='UTF-8' ?><XMLInfo>" .
                "<listNumber>{$listNumber}</listNumber><beginNumber>{$beginNumber}</beginNumber>" .
                "<param><activityMonth>{$month}</activityMonth><activityState>{$state}</activityState><activitySign>{$sign}</activitySign>" . 
                "</param></XMLInfo>";
        $result = $this->client->call('activityBudgetCost', array("in0"=>base64_encode($param)));
        //echo microtime(true)-$startTime;exit();
        $err = $this->client->getError();
        if ($err){
            $this->setError($err);
        }else{
            $xml = str_replace('&', '&amp;', $result['out']);
            $parser = new XMLParser($xml);
            $parser->Parse();
            //echo json_encode($parser->document);exit();
            if ($parser->document->globalinfo[0]->code[0]->tagData == 0 && $parser->document->return[0]->activity){
                $total = 0;//接口数据总数
                $updateCount = 0;//查询到的活动数据
                foreach ($parser->document->return[0]->activity as $activity){
                    $total ++;
                    //专营店数据
                    $storeData = $this->sellpointModel->getStoreDataByCode($activity->dlrno[0]->tagData);
                    if (!$storeData){//找不到专营店数据跳过
                        continue;
                    }
                    //时间段
                    $timeStamp = strtotime($year.'-'.$activity->activitymonth[0]->tagData.'-1 23:59:59');
                    $timeUnit = $this->timeUnitModel->getTimeUnit($timeStamp);
                    if (!$timeUnit){
                        continue;
                    }
                    //主线流程ID
                    $procId = $this->xunProcessModel->initData(array('storeId'=>$storeData['userId'], 'year'=>$year, 'timeUnit'=>$timeUnit));
                    //单店的主线流程也要自动生成，否则专营店没有入口进入查看
                    $this->singleProcessModel->initData(array('storeId'=>$storeData['userId'], 'year'=>$year, 'timeUnit'=>$timeUnit));
                    
                    $where = array(
                        'activityId'    => $activity->activityid[0]->tagData,
                    );
                    $data = array(
                        'storeId'       => (int)$storeData['userId'],//专营店ID
                        'year'          => $year,//年份
                        'timeUnit'      => $timeUnit,//时段ID
                        'procId'        => $procId,//主线流程ID
                        'orderId'       => (int)$activity->orderid[0]->tagData,//站点编号
                        'dlrNo'         => (string)$activity->dlrno[0]->tagData,//专营店编号
                        'activityName'  => (string)$activity->activityname[0]->tagData,//活动主题/试驾主题
                        'activityAddress' => (string)$activity->activityaddress[0]->tagData,//活动地址/车展地址
                        'activityTime'  => (string)$activity->activitytime[0]->tagData,//活动时间段/试驾时间
                        'activityType'  => (string)$activity->activitytype[0]->tagData,//活动类型
                        'activityCost'  => (float)$activity->activitycost[0]->tagData,//活动额度(项目定额)
                        'budgetApply'   => (float)$activity->activitytotalcost[0]->tagData,//预算总费用(预算申请金额)
                        'orderStatus'   => (string)$activity->orderstatus[0]->tagData,//站点状态
                        'siteSpecs'     => (int)$activity->sitespecs[0]->tagData,//巡展类型标志
                        'clearingPath'  => '',//结算凭证默认值不能为空
                    );
                    //过滤掉巡展类型标志非1的数据，过滤掉车展外场活动类型
                    if ($data['siteSpecs'] != 1 || $data['activityType'] == '车展外场') {
                        $this->recordLog(1, $where['activityId'], 0, $data['orderId'], 0, $data);
                        continue;
                    }
                    $projectData = $this->xProjectModel->getData($where);
                    if ($projectData){
                        $data['updateTime'] = time();
                        $this->xProjectModel->edit($where, $data);
                    }else{
                        $data['createTime'] = time();
                        $this->xProjectModel->add(array_merge($where, $data));
                    }
                    //重新计算金额
                    $this->xProjectModel->updateMoney($where['activityId']);
                    //若同步未同步过的数据，则记录同步日志
                    if ($sign == 0) {
                        $this->recordLog(1, $where['activityId'], 0, $data['orderId'], 1, $data);
                    }
                    $updateCount ++;
                    //usleep(1000);
                }
                
                $this->setSuccess('更新成功', array('total'=>$total,'updateCount'=>$updateCount));
            }else{
                $this->setSuccess("数据为空：".$parser->document->globalinfo[0]->message[0]->tagData);
            }
        }
        return $this->json;
    }
    /**
     * 广宣预算同步
     * @param int $year 年份
     * @param int $month 月份
     * @param number $listNumber 返回的最大行数（获取条数）
     * @param number $beginNumber 开始行数（表示页码，三观已毁）
     * @param string $state 项目状态（08为默认值，表示已申请结算，RMP这边只获取这个状态的数据）
     * @param number $sign 获取标识（0：待同步，1：已同步）
     * @return Ambigous <number, multitype:number string multitype: , string, unknown>
     */
    function budgetGxSync($year, $month, $listNumber = 10, $beginNumber=1, $state = '08', $sign = 0){
        $param = "<?xml version='1.0' encoding='UTF-8' ?><XMLInfo>" .
            "<listNumber>{$listNumber}</listNumber><beginNumber>{$beginNumber}</beginNumber>" .
            "<param><activityMonth>{$month}</activityMonth><activityState>{$state}</activityState><activitySign>{$sign}</activitySign>" .
            "</param></XMLInfo>";
        $result = $this->client->call('activityOnlineAdCost', array("in0"=>base64_encode($param)));
        $err = $this->client->getError();
        if ($err){
            $this->setError($err);
        }else{
            $xml = str_replace('&', '&amp;', $result['out']);
            $parser = new XMLParser($xml);
            $parser->Parse();
            //echo json_encode($parser->document);exit();
            if ($parser->document->globalinfo[0]->code[0]->tagData == 0 && $parser->document->return[0]->onlinactivitycost){
                $total = 0;//接口数据总数
                $updateCount = 0;//查询到的活动数据
                foreach ($parser->document->return[0]->onlinactivitycost as $onlinActivityCost){
                    $total ++;
                    //活动数据
                    $projectData = $this->xProjectModel->getData(array('activityId'=>$onlinActivityCost->activityid[0]->tagData));
                    //若没有对于的项目数据，则跳过同步
                    if (!$projectData){
                        continue;
                    }
                    //时间段
                    $timeStamp = strtotime($year.'-'.$onlinActivityCost->activitymonth[0]->tagData.'-1 23:59:59');
                    $timeUnit = $this->timeUnitModel->getTimeUnit($timeStamp);
                    
                    $where = array(
                        'costNo'        => (string)$onlinActivityCost->costno[0]->tagData,
                        'activityId'    => (string)$onlinActivityCost->activityid[0]->tagData,
                    );
                    $data = array(
                        'storeId'       => isset($projectData['storeId']) ? $projectData['storeId'] : 0,//专营店ID
                        'year'          => $year,//年份
                        'timeUnit'      => $timeUnit,//时段ID
                        'procId'        => isset($projectData['procId']) ? $projectData['procId'] : 0,//主线流程ID
                        'adType'        => $onlinActivityCost->adtype[0]->tagData,//媒体类型
                        'adName'         => $onlinActivityCost->adname[0]->tagData,//媒体名称
                        'adSpecification'   => $onlinActivityCost->adspecification[0]->tagData,//投放规格
                        'adTime'        => $onlinActivityCost->adtime[0]->tagData,//发布时间段
                        'adCount'       => $onlinActivityCost->adcount[0]->tagData,//发布频次
                        'budgetApply'   => (float)$onlinActivityCost->adcost[0]->tagData,//预计费用
                    );
                    $gxData = $this->xPGxModel->getData($where);
                    if ($gxData){
                        $data['updateTime'] = time();
                        $this->xPGxModel->edit($where, $data);
                    }else{
                        $data['createTime'] = time();
                        $this->xPGxModel->add(array_merge($where, $data));
                    }
                    //重新计算金额
                    $this->xPGxModel->updateMoney($where['costNo']);
                    //若同步未同步过的数据，则记录同步日志
                    if ($sign == 0) {
                        $this->recordLog(2, $where['activityId'], $where['costNo'], $projectData['orderId'], 1, $data);
                    }
                    $updateCount ++;
                    //usleep(1000);
                }
        
                $this->setSuccess('更新成功', array('total'=>$total,'updateCount'=>$updateCount));
            }else{
                $this->setSuccess("数据为空：".$parser->document->globalinfo[0]->message[0]->tagData);
            }
        }
        return $this->json;
    }
    /**
     * 线下活动预算同步
     * @param int $year 年份
     * @param int $month 月份
     * @param number $listNumber 返回的最大行数（获取条数）
     * @param number $beginNumber 开始行数（表示页码，三观已毁）
     * @param string $state 项目状态（08为默认值，表示已申请结算，RMP这边只获取这个状态的数据）
     * @param number $sign 获取标识（0：待同步，1：已同步）
     * @return Ambigous <number, multitype:number string multitype: , string, unknown>
     */
    function budgetOfflineSync($year, $month, $listNumber = 10, $beginNumber=1, $state = '08', $sign = 0){
        $param = "<?xml version='1.0' encoding='UTF-8' ?><XMLInfo>" .
            "<listNumber>{$listNumber}</listNumber><beginNumber>{$beginNumber}</beginNumber>" .
            "<param><activityMonth>{$month}</activityMonth><activityState>{$state}</activityState><activitySign>{$sign}</activitySign>" .
            "</param></XMLInfo>";
        $result = $this->client->call('offlineActivityCost', array("in0"=>base64_encode($param)));
        $err = $this->client->getError();
        if ($err){
            $this->setError($err);
        }else{
            $xml = str_replace('&', '&amp;', $result['out']);
            $parser = new XMLParser($xml);
            $parser->Parse();
            //echo json_encode($parser->document);exit();
            if ($parser->document->globalinfo[0]->code[0]->tagData == 0 && $parser->document->return[0]->offlineactivitycost){
                $total = 0;//接口数据总数
                $updateCount = 0;//查询到的活动数据
                foreach ($parser->document->return[0]->offlineactivitycost as $offlineActivityCost){
                    $total ++;
                    //活动数据
                    $projectData = $this->xProjectModel->getData(array('activityId'=>$offlineActivityCost->activityid[0]->tagData));
                    //若没有对于的项目数据，则跳过同步
                    if (!$projectData){
                        continue;
                    }
                    //时间段
                    $timeStamp = strtotime($year.'-'.$offlineActivityCost->activitymonth[0]->tagData.'-1 23:59:59');
                    $timeUnit = $this->timeUnitModel->getTimeUnit($timeStamp);
        
                    $where = array(
                        'costNo'        => (string)$offlineActivityCost->costno[0]->tagData,
                        'activityId'    => (string)$offlineActivityCost->activityid[0]->tagData,
                    );
                    $data = array(
                        'storeId'       => isset($projectData['storeId']) ? $projectData['storeId'] : 0,//专营店ID
                        'year'          => $year,//年份
                        'timeUnit'      => $timeUnit,//时段ID
                        'procId'        => isset($projectData['procId']) ? $projectData['procId'] : 0,//主线流程ID
                        'activityAddress'   => (string)$offlineActivityCost->activityaddress[0]->tagData,//活动地址
                        'activityTime'  => (string)$offlineActivityCost->activitytime[0]->tagData,//活动时间段
                        'budgetApply'   => (float)$offlineActivityCost->activitybudgetcost[0]->tagData,//预计费用
                    );
                    $offlineData = $this->xPOfflineModel->getData($where);
                    if ($offlineData){
                        $data['updateTime'] = time();
                        $id = $this->xPOfflineModel->edit($where, $data);
                    }else{
                        $data['createTime'] = time();
                        $id = $this->xPOfflineModel->add(array_merge($where, $data));
                    }
                    
                    //线下活动明细
                    if (isset($offlineActivityCost->activitybudgetcostdetailist[0]->activitybudgetcostdetail)){
                        $data['detailData'] = array();
                        foreach ((array)$offlineActivityCost->activitybudgetcostdetailist[0]->activitybudgetcostdetail as $offlineDetail){
                            $detailArr = explode('|', (string)$offlineDetail->tagData);
                            $detailData = array(
                                'storeId'       => isset($projectData['storeId']) ? $projectData['storeId'] : 0,//专营店ID
                                'year'          => $year,
                                'timeUnit'      => $timeUnit,
                                'offlineCostNo' => $where['costNo'],
                                'detailType'    => isset($detailArr[0]) ? (int)$detailArr[0] : 0,
                                'detailName'    => isset($detailArr[1]) ? (int)$detailArr[1] : 0,
                                'budgetApply'   => isset($detailArr[2]) ? (float)$detailArr[2] : 0,
                                'detailTime'    => isset($detailArr[3]) ? (string)$detailArr[3] : '',
                                'createTime'    => time(),
                            );
                            $data['detailData'][] = $detailData;
                        }
                        if ($data['detailData']) {
                            $this->xPODetailModel->del(array('offlineCostNo'=>$where['costNo']),'*');//删除旧数据
                            foreach ($data['detailData'] as $k => $v) {
                                if ($v['detailType'] || $v['detailName'] || $v['budgetApply'] ){
                                    $this->xPODetailModel->add($v);
                                }
                            }
                        }
                    }
                    //重新计算线下活动金额
                    $this->xPOfflineModel->updateMoney($where['costNo']);
                    //若同步未同步过的数据，则记录同步日志
                    if ($sign == 0) {
                        $this->recordLog(3, $where['activityId'], $where['costNo'], $projectData['orderId'], 1, $data);
                    }
                    $updateCount ++;
                    //usleep(1000);
                }
                
                $this->setSuccess('更新成功', array('total'=>$total,'updateCount'=>$updateCount));
            }else{
                $this->setSuccess("数据为空：".$parser->document->globalinfo[0]->message[0]->tagData);
            }
        }
        return $this->json;
    }
    /**
     * 项目结算同步
     * @param unknown $year 年份
     * @param unknown $month 月份
     * @param number $listNumber 返回的最大行数（获取条数）
     * @param number $beginNumber 开始行数（表示页码，三观已毁）
     * @param string $state 项目状态（08为默认值，表示已申请结算，RMP这边只获取这个状态的数据）
     * @param number $sign 获取标识（0：待同步，1：已同步）
     * @return Ambigous <number, multitype:number string multitype: , unknown, string>
     */
    function settleProjectSync($year, $month, $listNumber = 10, $beginNumber = 1, $state = '08', $sign = 0){
        $param = "<?xml version='1.0' encoding='UTF-8' ?><XMLInfo>" .
            "<listNumber>{$listNumber}</listNumber><beginNumber>{$beginNumber}</beginNumber>" .
            "<param><activityMonth>{$month}</activityMonth><activityState>{$state}</activityState><activitySign>{$sign}</activitySign>" .
            "</param></XMLInfo>";
        $result = $this->client->call('activityClearingCost', array("in0"=>base64_encode($param)));
        $err = $this->client->getError();
        if ($err){
            $this->setError($err);
        }else{
            $xml = str_replace('&', '&amp;', $result['out']);
            $parser = new XMLParser($xml);
            $parser->Parse();
            //echo json_encode($parser->document);exit();
            if ($parser->document->globalinfo[0]->code[0]->tagData == 0 && $parser->document->return[0]->activity){
                $total = 0;//接口数据总数
                $updateCount = 0;//查询到的活动数据
                foreach ($parser->document->return[0]->activity as $activity){
                    $total ++;
                    //专营店数据
                    $storeData = $this->sellpointModel->getStoreDataByCode($activity->dlrno[0]->tagData);
                    if (!$storeData){//找不到专营店数据跳过
                        continue;
                    }
                    //时间段
                    $timeStamp = strtotime($year.'-'.$activity->activitymonth[0]->tagData.'-1 23:59:59');
                    $timeUnit = $this->timeUnitModel->getTimeUnit($timeStamp);
                    if (!$timeUnit){
                        continue;
                    }
                    //主线流程ID
                    $procId = $this->xunProcessModel->initData(array('storeId'=>$storeData['userId'], 'year'=>$year, 'timeUnit'=>$timeUnit));
                    //单店的主线流程也要自动生成，否则专营店没有入口进入查看
                    $this->singleProcessModel->initData(array('storeId'=>$storeData['userId'], 'year'=>$year, 'timeUnit'=>$timeUnit));
                    
                    $where = array(
                        'activityId'    => $activity->activityid[0]->tagData,
                    );
                    $data = array(
                        'storeId'       => $storeData['userId'],//专营店ID
                        'year'          => $year,//年份
                        'timeUnit'      => $timeUnit,//时段ID
                        'procId'        => $procId,//主线流程ID
                        'orderId'       => (int)$activity->orderid[0]->tagData,//站点编号
                        'dlrNo'         => (string)$activity->dlrno[0]->tagData,//专营店编号
                        'activityName'  => (string)$activity->activityname[0]->tagData,//活动主题/试驾主题
                        'activityAddress' => (string)$activity->activityaddress[0]->tagData,//活动地址/车展地址
                        'activityTime'  => (string)$activity->activitytime[0]->tagData,//活动时间段/试驾时间
                        'activityType'  => $activity->activitytype[0]->tagData,//活动类型
                        'activityCost'  => (float)$activity->activitycost[0]->tagData,//活动额度(项目定额)
                        'budgetApply'   => (float)$activity->activitytotalcost[0]->tagData,//预算总费用(预算申请金额)
                        'orderStatus'   => (string)$activity->orderstatus[0]->tagData,//站点状态
                        'siteSpecs'     => (int)$activity->sitespecs[0]->tagData,//巡展类型标志
                        'settleApply'   => (float)$activity->clearingappcost[0]->tagData,//结算申请总费用
                        'clearingPath'  => (string)$activity->clearingpath[0]->tagData,//结算凭证
                        'settleAudit'   => (float)$activity->clearingcheckcost[0]->tagData,//结算审核金额
                        'kpi'           => (float)$activity->kpi[0]->tagData,//KPI系数
                        'settleMoney'   => (float)$activity->finalecost[0]->tagData,//结算金额
                    );
                    //过滤掉巡展类型标志非1的数据，过滤掉车展外场活动类型
                    if ($data['siteSpecs'] != 1 || $data['activityType'] == '车展外场') {
                        $this->recordLog(4, $where['activityId'], 0, $data['orderId'], 0, $data);
                        continue;
                    }
                    $projectData = $this->xProjectModel->getData($where);
                    //如已存在并且未审核，则结算审核状态变为待审核状态
                    if ($projectData){
                        $projectData['settleAuditRs'] == -1 && $data['settleAuditRs'] = 0;
                        $data['updateTime'] = time();
                        $this->xProjectModel->edit($where, $data);
                    }else{
                        $data['settleAuditRs'] = 0;
                        $data['createTime'] = time();
                        $this->xProjectModel->add(array_merge($where, $data));
                    }
                    //重新计算金额
                    $this->xProjectModel->updateMoney($where['activityId']);
                    //更新项目结算状态
                    $this->xProjectModel->settleUpdateStatus($where['activityId']);
                    //若同步未同步过的数据，则记录同步日志
                    if ($sign == 0) {
                        $this->recordLog(4, $where['activityId'], 0, $data['orderId'], 1, $data);
                    }
                    $updateCount ++;
                    //usleep(1000);
                }
                
                $this->setSuccess('更新成功', array('total'=>$total,'updateCount'=>$updateCount));
            }else{
                $this->setSuccess("数据为空：".$parser->document->globalinfo[0]->message[0]->tagData);
            }
        }
        return $this->json;
    }
    /**
     * 广宣结算同步
     * @param int $year 年份
     * @param int $month 月份
     * @param number $listNumber 返回的最大行数（获取条数）
     * @param number $beginNumber 开始行数（表示页码，三观已毁）
     * @param string $state 项目状态（08为默认值，表示已申请结算，RMP这边只获取这个状态的数据）
     * @param number $sign 获取标识（0：待同步，1：已同步）
     * @return Ambigous <number, multitype:number string multitype: , unknown, string>
     */
    function settleGxSync($year, $month, $listNumber = 10, $beginNumber=1, $state = '08', $sign = 0){
        $param = "<?xml version='1.0' encoding='UTF-8' ?><XMLInfo>" .
            "<listNumber>{$listNumber}</listNumber><beginNumber>{$beginNumber}</beginNumber>" .
            "<param><activityMonth>{$month}</activityMonth><activityState>{$state}</activityState><activitySign>{$sign}</activitySign>" .
            "</param></XMLInfo>";
        $result = $this->client->call('activityOnlineAdClearing', array("in0"=>base64_encode($param)));
        $err = $this->client->getError();
        if ($err){
            $this->setError($err);
        }else{
            $xml = str_replace('&', '&amp;', $result['out']);
            $parser = new XMLParser($xml);
            $parser->Parse();
            //echo json_encode($parser->document);exit();
            if ($parser->document->globalinfo[0]->code[0]->tagData == 0 && $parser->document->return[0]->onlinactivitycost){
                $total = 0;//接口数据总数
                $updateCount = 0;//查询到的活动数据
                foreach ($parser->document->return[0]->onlinactivitycost as $onlinActivityCost){
                    $total ++;
                    //活动数据
                    $projectData = $this->xProjectModel->getData(array('activityId'=>$onlinActivityCost->activityid[0]->tagData));
                    //若没有对于的项目数据，则跳过同步
                    if (!$projectData){
                        continue;
                    }
                    //时间段
                    $timeStamp = strtotime($year.'-'.$onlinActivityCost->activitymonth[0]->tagData.'-1 23:59:59');
                    $timeUnit = $this->timeUnitModel->getTimeUnit($timeStamp);
    
                    $where = array(
                        'costNo'        => (string)$onlinActivityCost->costno[0]->tagData,
                        'activityId'    => (string)$onlinActivityCost->activityid[0]->tagData,
                    );
                    $data = array(
                        'storeId'       => isset($projectData['storeId']) ? $projectData['storeId'] : 0,//专营店ID
                        'year'          => $year,//年份
                        'timeUnit'      => $timeUnit,//时段ID
                        'procId'        => isset($projectData['procId']) ? $projectData['procId'] : 0,//主线流程ID
                        'adType'        => (string)$onlinActivityCost->adtype[0]->tagData,//媒体类型
                        'adName'         => (string)$onlinActivityCost->adname[0]->tagData,//媒体名称
                        'adSpecification'   => (string)$onlinActivityCost->adspecification[0]->tagData,//投放规格
                        'adTime'        => (string)$onlinActivityCost->adtime[0]->tagData,//发布时间段
                        'adCount'       => (string)$onlinActivityCost->adcount[0]->tagData,//发布频次
                        'budgetApply'   => (float)$onlinActivityCost->adcost[0]->tagData,//预计费用
                        'settleApply'   => (float)$onlinActivityCost->adclearingcost[0]->tagData,//实际费用
                    );
                    $gxData = $this->xPGxModel->getData($where);
                    if ($gxData){
                        $gxData['settleAuditRs'] == -1 && $data['settleAuditRs'] = 0;//结算变成申请状态
                        //如果已审核通过，则直接将审核申请金额变成审核通过金额
                        in_array($gxData['settleAuditRs'], array(1,4)) && $data['settleAudit'] = $data['settleApply'];
                        $data['updateTime'] = time();
                        $this->xPGxModel->edit($where, $data);
                    }else{
                        $data['settleAuditRs'] = 0;//结算变成申请状态
                        $data['createTime'] = time();
                        $this->xPGxModel->add(array_merge($where, $data));
                    }
                    //重新计算金额
                    $this->xPGxModel->updateMoney($where['costNo']);
                    //若同步未同步过的数据，则记录同步日志
                    if ($sign == 0) {
                        $this->recordLog(5, $where['activityId'], $where['costNo'], $projectData['orderId'], 1, $data);
                    }
                    $updateCount ++;
                    //usleep(1000);
                }
    
                $this->setSuccess('更新成功', array('total'=>$total,'updateCount'=>$updateCount));
            }else{
                $this->setSuccess("数据为空：".$parser->document->globalinfo[0]->message[0]->tagData);
            }
        }
        return $this->json;
    }
    /**
     * 线下活动结算同步
     * @param int $year 年份
     * @param int $month 月份
     * @param number $listNumber 返回的最大行数（获取条数）
     * @param number $beginNumber 开始行数（表示页码，三观已毁）
     * @param string $state 项目状态（08为默认值，表示已申请结算，RMP这边只获取这个状态的数据）
     * @param number $sign 获取标识（0：待同步，1：已同步）
     * @return Ambigous <number, multitype:number string multitype: , string, unknown>
     */
    function settleOfflineSync($year, $month, $listNumber = 10, $beginNumber=1, $state = '08', $sign = 0){
        $param = "<?xml version='1.0' encoding='UTF-8' ?><XMLInfo>" .
            "<listNumber>{$listNumber}</listNumber><beginNumber>{$beginNumber}</beginNumber>" .
            "<param><activityMonth>{$month}</activityMonth><activityState>{$state}</activityState><activitySign>{$sign}</activitySign>" .
            "</param></XMLInfo>";
        $result = $this->client->call('offlineActivityClearing', array("in0"=>base64_encode($param)));
        $err = $this->client->getError();
        if ($err){
            $this->setError($err);
        }else{
            $xml = str_replace('&', '&amp;', $result['out']);
            $parser = new XMLParser($xml);
            $parser->Parse();
            //echo json_encode($parser->document);exit();
            if ($parser->document->globalinfo[0]->code[0]->tagData == 0 && $parser->document->return[0]->offlineactivitycost){
                $total = 0;//接口数据总数
                $updateCount = 0;//查询到的活动数据
                foreach ($parser->document->return[0]->offlineactivitycost as $offlineActivityCost){
                    $total ++;
                    //活动数据
                    $projectData = $this->xProjectModel->getData(array('activityId'=>$offlineActivityCost->activityid[0]->tagData));
                    //若没有对于的项目数据，则跳过同步
                    if (!$projectData){
                        continue;
                    }
                    //时间段
                    $timeStamp = strtotime($year.'-'.$offlineActivityCost->activitymonth[0]->tagData.'-1 23:59:59');
                    $timeUnit = $this->timeUnitModel->getTimeUnit($timeStamp);
    
                    $where = array(
                        'costNo'        => (string)$offlineActivityCost->costno[0]->tagData,
                        'activityId'    => (string)$offlineActivityCost->activityid[0]->tagData,
                    );
                    $data = array(
                        'storeId'       => isset($projectData['storeId']) ? $projectData['storeId'] : 0,//专营店ID
                        'year'          => $year,//年份
                        'timeUnit'      => $timeUnit,//时段ID
                        'procId'        => isset($projectData['procId']) ? $projectData['procId'] : 0,//主线流程ID
                        'activityAddress'   => (string)$offlineActivityCost->activityaddress[0]->tagData,//活动地址
                        'activityTime'  => (string)$offlineActivityCost->activitytime[0]->tagData,//活动时间段
                        'budgetApply'   => (float)$offlineActivityCost->activitybudgetcost[0]->tagData,//预计费用
                        'settleApply'   => (float)$offlineActivityCost->activityclearingcost[0]->tagData,//实际费用
                    );
                    $offlineData = $this->xPOfflineModel->getData($where);
                    if ($offlineData){
                        $offlineData['settleAuditRs'] == -1 && $data['settleAuditRs'] = 0;//结算变成申请状态
                        //如果已审核通过，则直接将审核申请金额变成审核通过金额
                        in_array($offlineData['settleAuditRs'], array(1,4)) && $data['settleAudit'] = $data['settleApply'];
                        $data['updateTime'] = time();
                        $this->xPOfflineModel->edit($where, $data);
                    }else{
                        $data['settleAuditRs'] = 0;//结算变成申请状态
                        $data['createTime'] = time();
                        $this->xPOfflineModel->add(array_merge($where, $data));
                    }
    
                    //线下活动明细
                    if (isset($offlineActivityCost->activityclearingcostdetaillist[0]->activityclearingcostdetail)){
                        $data['detailData'] = array();
                        foreach ((array)$offlineActivityCost->activityclearingcostdetaillist[0]->activityclearingcostdetail as $offlineDetail){
                            $detailArr = explode('|', (string)$offlineDetail->tagData);
                            $detailData = array(
                                'storeId'       => isset($projectData['storeId']) ? $projectData['storeId'] : 0,//专营店ID
                                'year'          => $year,
                                'timeUnit'      => $timeUnit,
                                'offlineCostNo' => $where['costNo'],
                                'detailType'    => isset($detailArr[0]) ? (int)$detailArr[0] : '',//费用明细类型
                                'detailName'    => isset($detailArr[1]) ? (int)$detailArr[1] : '',//费用明细名称
                                'budgetApply'   => isset($detailArr[2]) ? (float)$detailArr[2] : 0,//预算申请金额
                                'settleApply'   => isset($detailArr[3]) ? (float)$detailArr[3] : 0,//结算申请金额
                                'detailTime'    => isset($detailArr[4]) ? (string)$detailArr[4] : '',//活动时间段
                                'createTime'    => time(),
                            );
                            $data['detailData'][] = $detailData;
                        }
                        if ($data['detailData']) {
                            $this->xPODetailModel->del(array('offlineCostNo'=>$where['costNo']), '*');//删除旧数据
                            foreach ($data['detailData'] as $k => $v) {
                                if ($v['detailType'] || $v['detailName'] || $v['budgetApply'] || $v['settleApply'] ){
                                    $this->xPODetailModel->add($v);
                                }
                            }
                        }
                    }
                    //重新计算线下活动金额
                    $this->xPOfflineModel->updateMoney($where['costNo']);
                    //若同步未同步过的数据，则记录同步日志
                    if ($sign == 0) {
                        $this->recordLog(6, $where['activityId'], $where['costNo'], $projectData['orderId'], 1, $data);
                    }
                    $updateCount ++;
                    //usleep(1000);
                }
    
                $this->setSuccess('更新成功', array('total'=>$total,'updateCount'=>$updateCount));
            }else{
                $this->setSuccess("数据为空：".$parser->document->globalinfo[0]->message[0]->tagData);
            }
        }
        return $this->json;
    }
    /**
     * 记录巡展同步数据日志
     * @param  number $type       [description]
     * @param  string $activityId [description]
     * @param  string $costNo     [description]
     * @param  array  $data       [description]
     * @return [type]             [description]
     */
    function recordLog($type, $activityId='', $costNo='', $orderId, $isSync = 0, $data = array()){
        require_once APPPATH.'libraries/JSON.php';
        $json = new Services_JSON();
        $logData = array(
            'type' => $type,
            'activityId' => $activityId,
            'costNo' => $costNo,
            'orderId' => $orderId,
            'isSync' => $isSync,
            'data' => $json->encode($data),
            'createTime' => date('Y-m-d H:i:s'),
            );
        $this->xDataLogModel->add($logData);
    }
}